<!-- LayoutPageBar -->
<template>
  <div
    class="LayoutPageBar"
    onselectstart="return false;"
    style="-moz-user-select:none;"
  >
    <div class="pagesList">
      <el-tag
        type="info"
        size="small"
        effect="dark"
        hit
        :class="CurrentPage.path === '/dashbord' ? 'action' : ''"
        @click="tagClick('/dashbord')"
        @contextmenu.native.prevent
      >
        <i class="el-icon-s-home"></i> 首页
      </el-tag>
      <el-tag
        v-for="(item, index) in pageTags"
        :key="item.path"
        :ref="`Tag_${index}`"
        :data-path="item.path"
        size="small"
        :class="CurrentPage.path === item.path ? 'action' : ''"
        closable
        effect="dark"
        type="info"
        hit
        @click="tagClick(item.path)"
        @close="tagClose(item, index)"
        @contextmenu.native.prevent="
          handleClickContextMenu($event, item, index)
        "
      >
        <i v-if="item.meta.icon" :class="item.meta.icon"></i>
        {{ item.meta.title }}
      </el-tag>
    </div>
    <div
      class="rightMenu"
      :style="{ left: menuLeft, top: menuTop }"
      v-show="rightMenuVisible"
    >
      <div class="triangle"></div>
      <el-button
        type="text"
        class="rightMenuItem"
        :disabled="MenuStatus.refreshAble"
        @click="refresh"
        >刷新</el-button
      >
      <el-button
        type="text"
        class="rightMenuItem"
        :disabled="MenuStatus.closeOtherAble"
        @click="closeOther"
        >关闭其它</el-button
      >
      <el-button
        type="text"
        class="rightMenuItem"
        :disabled="MenuStatus.closeLeftAble"
        @click="closeLeft"
        >关闭左侧</el-button
      >
      <el-button
        type="text"
        class="rightMenuItem"
        :disabled="MenuStatus.closeRightAble"
        @click="closeRight"
        >关闭右侧</el-button
      >
      <el-button type="text" class="rightMenuItem" @click="closeAll"
        >全部关闭</el-button
      >
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState } from "vuex";
export default {
  name: "LayoutPageBar",
  inject: ["reload"],
  components: {},
  data() {
    return {
      PagesListDom: null,
      // 是否来自pageBar自身的点击
      formTagClick: false,
      // 被右键选中的tag
      rightClick_Tag: null,
      rightClick_Index: null,
      rightMenuVisible: false,
      // 右键菜单定位数据
      menuLeft: 0,
      menuTop: 0,
      // 右键菜单状态
      MenuStatus: {
        refreshAble: true,
        closeOtherAble: true,
        closeLeftAble: true,
        closeRightAble: true
      }
    };
  },
  computed: {
    ...mapState("Layout", ["CurrentPage", "pageTags"])
  },
  watch: {
    // 通过监听路由变化控制tag定位
    CurrentPage: {
      handler(newValue) {
        if (this.formTagClick) {
          this.formTagClick = false;
          return;
        }
        // 解决新增tag时DOM未更新完成获取不到偏移值，滚动条无法定位。妙不可言
        this.$nextTick(() => {
          this.tagFixed(newValue.path);
        });
      },
      deep: true
    }
  },
  //方法集合
  methods: {
    ...mapMutations("Layout", [
      "addCachePage",
      "delCachePage",
      "closePageTag",
      "closeOtherTag",
      "closeLeftTag",
      "closeRightTag",
      "closeAllTag"
    ]),
    // 滚动条控制
    OnMousewheel(e) {
      let eventDelta = -e.wheelDelta || -e.deltaY * 40;
      this.PagesListDom.scrollLeft =
        this.PagesListDom.scrollLeft + eventDelta / 2;
    },
    // tag点击
    tagClick(path) {
      this.closeRightMenu();
      this.formTagClick = true;
      this.$router.push(path);
    },
    // tag关闭
    tagClose(item, index) {
      // console.log(path, index);
      this.closeRightMenu();
      let pagesBarLength = this.pageTags.length;
      if (pagesBarLength === 1) {
        this.$router.push("/");
      } else if (item.path == this.CurrentPage.path) {
        let nextAction =
          index < pagesBarLength - 1
            ? index + 1
            : index === pagesBarLength - 1
            ? index - 1
            : 0;
        let currentItem = this.pageTags[nextAction];
        this.$router.push(currentItem.path);
      }
      // 清除keepalive缓存
      this.delCachePage(item.name);
      this.closePageTag(index);
    },
    // tag右键
    handleClickContextMenu(e, item, index) {
      let _MenuStatus = {
        refreshAble: false,
        closeOtherAble: false,
        closeLeftAble: false,
        closeRightAble: false
      };
      // const e = event || window.event;
      this.rightClick_Tag = item;
      this.rightClick_Index = index;
      this.menuLeft = e.clientX + "px";
      this.menuTop = e.clientY + 20 + "px";

      let TagsLength = this.pageTags.length;

      // 只有一项
      if (TagsLength === 1) {
        _MenuStatus.closeOtherAble = true;
        _MenuStatus.closeLeftAble = true;
        _MenuStatus.closeRightAble = true;
      }
      // 多项第一项
      else if (index === 0 && TagsLength > 1) {
        _MenuStatus.closeLeftAble = true;
      }
      // 多项最后一项
      else if (index === TagsLength - 1 && TagsLength > 1) {
        _MenuStatus.closeRightAble = true;
      }
      // 仅当前页可刷新
      _MenuStatus.refreshAble =
        this.CurrentPage.path === item.path ? false : true;
      this.MenuStatus = _MenuStatus;
      this.rightMenuVisible = true; // 显示菜单
    },
    // 刷新
    refresh() {
      // 刷新时清除本页缓存
      this.delCachePage(this.rightClick_Tag.name);
      this.$nextTick(() => {
        !this.rightClick_Tag.meta.notKeep &&
          this.addCachePage(this.rightClick_Tag.name);
      });
      this.reload();
      this.closeRightMenu();
    },
    closeOther() {
      this.closeOtherTag(this.rightClick_Tag.path);
      if (this.rightClick_Tag.path != this.CurrentPage.path) {
        this.$router.push(this.rightClick_Tag.path);
      }
      this.closeRightMenu();
    },
    closeLeft() {
      let currentIndex = this.actionPageIndex();
      if (currentIndex < this.rightClick_Index) {
        this.$router.push(this.rightClick_Tag.path);
      }
      this.closeLeftTag(this.rightClick_Index);
      this.closeRightMenu();
    },
    closeRight() {
      let currentIndex = this.actionPageIndex();
      if (currentIndex > this.rightClick_Index) {
        this.$router.push(this.rightClick_Tag.path);
      }
      this.closeRightTag(this.rightClick_Index);
      this.closeRightMenu();
    },
    closeAll() {
      this.$router.push("/");
      this.closeAllTag();
      this.closeRightMenu();
    },
    // 关闭右键菜单
    closeRightMenu() {
      this.rightMenuVisible = false;
    },
    // 左侧/右侧 关闭时判断actionPage是否在其中
    actionPageIndex() {
      return this.pageTags.findIndex(item => {
        return item.path === this.CurrentPage.path;
      });
    },
    // 根据路由定位tag
    tagFixed(path) {
      let offsetLeft = 0;
      let refs = this.$refs;
      for (let key in refs) {
        if (!refs[key].length) continue;
        let $el = refs[key][0].$el;
        if (path == $el.dataset.path) {
          offsetLeft = $el.offsetLeft;
          break;
        }
      }
      this.PagesListDom.scrollLeft = offsetLeft;
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.PagesListDom = document.querySelector(".pagesList");
    //监听鼠标滚动事件
    this.PagesListDom.addEventListener("mousewheel", this.OnMousewheel) ||
      this.PagesListDom.addEventListener("DOMMouseScroll", this.OnMousewheel);

    // 全局点击其它元素关闭
    window.addEventListener("click", () => {
      this.closeRightMenu();
    });
    // 窗口缩放关闭
    window.addEventListener("resize", () => {
      this.closeRightMenu();
    });
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="scss" scoped>
.LayoutPageBar {
  // height: 36px;

  .pagesList {
    padding-bottom: 5px;
    margin-bottom: 2px;
    overflow: auto;
    display: flex;
    position: relative;
    flex-wrap: nowrap;
    scroll-behavior: smooth;
    &:hover {
      // 滚轮滑动滚动条时取消平滑过渡，否则出现滑动效率低现象
      scroll-behavior: auto;
    }
    > :first-child {
      margin-left: 0 !important;
    }

    > :last-child {
      margin-right: 0 !important;
    }

    .el-tag {
      margin: 0 5px;
      cursor: pointer;

      &.action {
        background: $ThemeActiveText;
        border: 1px solid $ThemeActiveText;
      }
    }
  }
  .rightMenu {
    width: 100px;
    height: 158px;
    padding: 10px 0;
    background: #fffefe;
    position: absolute;
    z-index: 2;
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0 4px 7px 0 rgba(0, 0, 0, 0.3);

    .triangle {
      width: 0;
      height: 0;
      border: 8px solid;
      border-color: transparent transparent #fff;
      position: absolute;
      top: -16px;
      left: 14px;
    }

    .rightMenuItem {
      display: block;
      width: 100%;
      margin: 0;
      text-align: left;
      padding: 0 20px;
      line-height: 26px;
      font-size: 14px;
      color: $ThemeActiveText;

      // cursor: pointer;
      &.is-disabled {
        color: #c0c4cc;

        &:hover {
          background: none;
        }
      }

      &:hover {
        background: #f5f7fa;
      }
    }
  }
}

/*滚动条的宽度*/
::-webkit-scrollbar {
  height: 2px;
}

/*外层轨道*/
::-webkit-scrollbar-track {
  display: none;
}

/*滚动条的设置*/

::-webkit-scrollbar-thumb {
  background-color: #445468;
  background-clip: padding-box;
}

/*滚动条移上去的背景*/
.LayoutPageBar:hover ::-webkit-scrollbar-thumb {
  background-color: $ThemeActiveText;
}

::-webkit-scrollbar-thumb:hover {
  background-color: $ThemeActiveText;
  cursor: pointer;
}
</style>
